﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleRest.Core
{
    /// <summary>
    /// Logical representation of a service operation.
    /// </summary>
    public class Operation
    {
        public Operation(string name, Type returnType, string uriTemplate, System.Reflection.MethodInfo method, string httpMethod, IEnumerable<OperationParameter> parameters)
        {
            this.Name = name;
            this.Parameters = parameters;
            this.ReturnType = returnType;
            this.UriTemplate = uriTemplate;
            this.TargetMethod = method;
            this.HttpMethod = httpMethod;
        }

        /// <summary>
        /// The name of the operation for a particular service.
        /// </summary>
        public string Name { get; private set; }
        /// <summary>
        /// The list of input parameters for the associated operation.
        /// </summary>
        public IEnumerable<OperationParameter> Parameters { get; private set; }
        /// <summary>
        /// The return type for the operation.
        /// </summary>
        public Type ReturnType { get; private set; }
        /// <summary>
        /// The Uri route template associated to this service operation.
        /// </summary>
        public string UriTemplate { get; private set; }
        /// <summary>
        /// The target method associated to this operation
        /// </summary>
        public System.Reflection.MethodInfo TargetMethod { get; private set; }
        /// <summary>
        /// The http method associated to this operation
        /// </summary>
        public string HttpMethod { get; private set; }
    }

    public static class OperationExtensions
    {
        public static OperationParameter GetHttpBodyParameter(this IEnumerable<OperationParameter> items)
        {
            if (items == null || !items.Any())
                return null;

            foreach (var param in items)
            {
                foreach (var obj in param.Type.GetCustomAttributes(true))
                {
                    if (obj is HttpBodyAttribute)
                    {
                        return param;
                    }
                }
            }

            return null;
        }
    }
}
